package com.stockz.ui.swing.watchlist.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.core.manager.ImportExportManager;
import com.stockz.ui.swing.core.MainFrame;
import com.stockz.ui.swing.widget.JMenuItem;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;

@Component
public class ExportWatchListMenuItem extends JMenuItem implements ActionListener {
	private static final long serialVersionUID = 8288877209248392115L;
	
	@Autowired
	private ImportExportManager importExportManager;
	@Autowired
	private WatchListManager watchListManager;
	
	public ExportWatchListMenuItem() {
		super("Export All");
		addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		 JFileChooser chooser = new JFileChooser();
		 FileFilter filter = new FileFilter(){
			@Override
			public boolean accept(File pathname) {
					return pathname.getName().endsWith("xml");
			}
			
			@Override
			public String getDescription() {
				return "xml";
			}
		 };

		 chooser.setFileFilter(filter);
		 if(chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
			 try {
				 List<WatchList> watchListList = watchListManager.getAll();
				 if(watchListList != null && !watchListList.isEmpty()){
					 for(WatchList watchList : watchListList){
						 watchList.getEntryList().addAll(watchListManager.getByWatchListId(watchList.getId()));
					 }
				 }
				 String path = chooser.getSelectedFile().getAbsolutePath();
				 if(!path.endsWith(".xml")) path += ".xml";
				importExportManager.exportData(path, watchListList);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(MainFrame.getInstance(),
					    e1.getMessage(),
					    "Error",
					    JOptionPane.ERROR_MESSAGE);
			}
		 }
	}
	
}
